package com.ee.chat.api.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ee.chat.api.common.CommonService;
import com.ee.chat.api.service.IBaseService;
import com.ee.chat.api.vo.EquipmentVO;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.*;
import com.ee.chat.common.entity.SysVersion;
import com.ee.chat.common.entity.User;
import com.ee.chat.common.entity.UserCallLog;
import com.ee.chat.common.serconfig.MyAliOSSConfig;
import com.ee.chat.common.serconfig.MyAliSMSConfig;
import com.ee.chat.common.serconfig.MyAliSTSConfig;
import com.ee.chat.common.serconfig.MyNeteaseApp;
import com.ee.chat.common.util.ConstantsUtil;
import com.ndhutu.ee.util.IPUtil;
import com.ndhutu.ee.util.StringUtil;
import com.ndhutu.ee.util.ValidatorUtil;
import com.ndhutu.ee.util.ali.oss.OSSUtil;
import com.ndhutu.ee.util.ali.sms.SMSUtil;
import com.ndhutu.ee.util.ali.sts.STSUtil;
import com.ndhutu.ee.util.http.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author Shane
 * @Date 2019/7/23 14:46
 */
@Service
public class BaseServiceImpl implements IBaseService {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "stringRedisTemplate")
    StringRedisTemplate redisTemplate;
    @Resource
    UserMapper userMapper;
    @Resource
    MyAliSTSConfig stsConfig;
    @Resource
    MyAliOSSConfig ossConfig;
    @Resource
    SysVersionMapper sysVersionMapper;
    @Resource
    MyAliSMSConfig smsConfig;
    @Resource
    UserCallLogMapper userCallLogMapper;
    @Resource
    SysConfigMapper sysConfigMapper;
    @Resource
    CommonService commonService;
    @Resource
    BaseMapper baseMapper;
    @Resource
    MyNeteaseApp app;

    @Value("${spring.profiles.active}")
    String active;
    @Value("${ali.sms.loginTemplateCode}")
    String loginTemplateCode;

    @Override
    public Result sendCode(String token, String phone, String op) throws Exception {
        Map<String, Object> data = new HashMap<>();

        if(!ValidatorUtil.verifyPhone(phone)){
            return Result.returnFailure("请输入正确的手机号");
        }

        if("bind".equals(op)){
            Integer userId = commonService.getUserId(token);
            if(userId == null){
                return Result.returnTokenExpiry();
            }

            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone).ne("id", userId);
            if(userMapper.selectOne(wrapper) != null){
                return Result.returnFailure("该手机号已经被使用，请更换手机号");
            }
        }

        String key = ConstantsUtil.DATA_CODE + op + ":" + phone;
        String code = StringUtil.getRandomNumberStr();

        if("dev".equals(active)){
            code = "123456";
        }else{
            User user = userMapper.selectByPhone(phone);
            if(user != null && user.getRole() != 0){
                code = "123456";
            }else{
                Map<String, String> params = new HashMap<>();
                params.put("code", code);
                String res = SMSUtil.sendSms(smsConfig, phone, loginTemplateCode, params);
                if(!StringUtil.isEmpty(res)){
                    return Result.returnFailure(res);
                }
            }
        }

        redisTemplate.opsForHash().put(key, "code", code);
        redisTemplate.expire(key, 5, TimeUnit.MINUTES);
        userMapper.addPhoneCode(phone, code);

//        data.put("code", code);
        log.info("手机号："+phone+"，验证码："+code);

        return Result.returnSuccess(data);
    }

    @Override
    public Result getUploadToken(HttpServletRequest request, String fileName) throws Exception{
        Map<String, Object> data = new HashMap<>();

//        String uploadToken = NOSUtil.getUploadToken(nosService.getNosConfig(), fileName);
//
//        data.put("uploadToken", uploadToken);
//        data.put("bucket", nosService.getNosConfig().getBucket());

        Map<String, Object> sts = STSUtil.provisionalAuthority(stsConfig, ossConfig);
        data.put("sts", sts);

        return Result.returnSuccess(data);
    }

    @Override
    public Result getUploadSign(HttpServletRequest request) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Map<String, String> sign = OSSUtil.getSignature(ossConfig);
        data.put("sign", sign);
        return Result.returnSuccess(data);
    }

    /**
     * 获取基本信息
     * @Author Shane
     * @Date 2020/3/27 14:30
     * @param
     * @return
     */
    @Override
    public Result getBaseInfo(String token, String extra) throws Exception {
        Map<String, Object> data = new HashMap<>();

        String host = "https://"+ossConfig.getBucketName()+"."+ossConfig.getEndpoint();
        String h5Domain = sysConfigMapper.getValue("h5_domain");

        //判断功能隐藏状态
        Integer funHide = 0;
        Map<String, Object> extraMap = JSONObject.parseObject(extra, Map.class);
        String auditControl = sysConfigMapper.getValue("audit_control");
        if(!StringUtil.isEmpty(auditControl)){
            List<Map<String, Object>> audits = JSONArray.parseObject(auditControl, List.class);
            for(Map<String, Object> audit : audits){
                if(extraMap.get("platform").equals(audit.get("platform")) && StringUtil.compareVersion(extraMap.get("appVersion")+"", audit.get("appVersion")+"") >= 0){
                    funHide = Integer.parseInt(audit.get("hide")+"");
                }
            }
        }

        data.put("host", host);
        data.put("h5Domain", h5Domain);
        data.put("funHide", funHide);
        data.put("imPrefix", app.getIdPrefix());

        if(!StringUtil.isEmpty(token)){
            Integer userId = commonService.getUserId(token);
            if(userId == null){
                return Result.returnTokenExpiry();
            }

            User user = userMapper.selectById(userId);
            if(user.getGender() == 0){
                data.put("must", 1);

                Map<String, Object> map = new HashMap<>();
                map.put("icon", user.getIcon());
                map.put("name", user.getName());
                map.put("gender", 1);
                map.put("default_man_icon", sysConfigMapper.getValue("default_man_icon"));
                map.put("default_woman_icon", sysConfigMapper.getValue("default_woman_icon"));
                data.put("user", map);
            }else{
                data.put("must", 0);
            }
        }

        return Result.returnSuccess(data);
    }

    @Override
    public Result verifySensitiveWord(String token, String list) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Set<String> wordLib = redisTemplate.opsForSet().members("data:sensitiveWord");
        Boolean flag = true;
        for(String word : wordLib){
            int index = list.indexOf(word);
            if(index > -1){
                flag = false;
                break;
            }
        }
        if(flag){
            data.put("status", 0);
        }else{
            data.put("status", 1);
        }

        return Result.returnSuccess(data);
    }

    @Override
    public Result getNewestVersion(Integer type) throws Exception {
        Map<String, Object> data = new HashMap<>();

        SysVersion sysVersion = sysVersionMapper.selectNewestVersionByType(type);
        data.put("version", sysVersion);

        return Result.returnSuccess(data);
    }

    @Override
    public Result ossCallback(HttpServletRequest request) throws Exception {
        log.info("OSS上传回调开始-----------------");

        String result = RequestUtil.getResult(request);
        log.info("消息内容："+result);

        Map body = JSONObject.parseObject(result, Map.class);
        Integer type = Integer.parseInt(body.get("type")+"");


        if(type == 0){  //视频通话文件上传
            String channelId = body.get("channelId")+"";
            String url = body.get("url")+"";

            UserCallLog userCallLog = userCallLogMapper.selectByChannelId(channelId);
            if(userCallLog.getFile() == null){
                userCallLog.setFile(url);

                userCallLogMapper.updateById(userCallLog);
            }
        }

        return Result.returnSuccess(null);
    }

    /**
     * 添加访问记录
     * @Author Shane
     * @Date 2020/5/23 13:13
     * @param
     * @return
     */
    @Override
    public void addAccessLog(Integer userId, Integer toUserId) throws Exception {
        String date = LocalDate.now().toString();
        Map<String, Object> map = baseMapper.selectUserAccessLog(userId, toUserId);
        if(map == null){
            baseMapper.addUserAccessLog(userId, toUserId);
        }else{
            baseMapper.updateUserAccessLog(userId, toUserId);
        }
    }

    @Override
    public Result addClickLog(HttpServletRequest request, EquipmentVO equipment) throws Exception {
        String ip = IPUtil.getClientIP(request);

        if(!StringUtil.isEmpty(ip)){
            for(String i : ip.split(",")){
                i = i.trim();
                String key = "data:ip:"+i;

                redisTemplate.opsForSet().add(key, JSONObject.toJSONString(equipment));

                log.info("ip:"+i+"记录信息，"+JSONObject.toJSONString(equipment));

                redisTemplate.expire(key, 30, TimeUnit.DAYS);
            }
        }

        return Result.returnSuccess(null);
    }
}
